import { FISHING_METHOD_OPTIONS } from "../../constants/fishing";
import { updateFishingSession } from "../../api/fishing-session";

const defalutData = {
  timerange: "09:00-18:00",
  fishingway: FISHING_METHOD_OPTIONS[0].value,
  promotion: "",
};

Component({
  properties: {
    editable: { type: Boolean, value: false },
    // 放钓信息
    spotId: { type: String, value: "" },
    sessionData: {
      type: Object,
      value: {
        timerange: "",
        fishingway: "",
        promotion: "",
      },
    },
  },

  data: {
    methodOptions: FISHING_METHOD_OPTIONS,
    // 编辑中的数据
    formData: {
      ...defalutData,
    },
    selfEditable: false,
  },

  lifetimes: {
    attached() {
      // 初始化编辑数据
      console.log("======attached", this.properties.sessionData);
      this.setData({
        formData: { ...this.properties.sessionData },
      });
    },
  },

  methods: {
    // 打开编辑弹框
    onChangeEditMode() {
      this.setData({
        selfEditable: true,
        formData: { ...this.properties.sessionData },
      });
    },

    // 输入框
    onInputChange(e) {
      const { field } = e.currentTarget.dataset;
      // console.log("---field------", field, e.detail.value);
      this.setData({
        [`${field}`]: e.detail.value,
      });
      if (this.data.selfEditable) {
        return;
      }
      setTimeout(() => {
        this.triggerEvent("save", {
          data: {
            ...this.data.formData,
          },
        });
      }, 10);
    },
    // 保存修改
    async onSubmit() {
      const data = this.validateForm();
      if (!data) {
        return;
      }
      wx.showLoading({ title: "保存中..." });
      console.log("----data----", data);
      const res = await updateFishingSession(this.properties.spotId, data);
      console.log("----res----", res);
      wx.hideLoading();
      if (res.error) {
        wx.showToast("保存失败");
        return;
      }
      wx.showToast({
        title: "保存成功",
      });
      this.onCancel();
    },
    // 取消编辑
    onCancel() {
      this.setData({
        selfEditable: false,
      });
    },

    validateForm() {
      const { formData } = this.data;
      const array = [
        { key: "timerange", title: "请选择放钓时间" },
        { key: "fishingway", title: "请选择放钓方式" },
      ];
      const data = formData;
      for (let index = 0; index < array.length; index++) {
        const item = array[index];
        const { key, title } = item;
        if (!formData[key] || formData[key].trim() === "") {
          wx.showToast({
            title,
            icon: "none",
          });
          return false;
        }
        data[key] = formData[key].trim();
      }
      return data;
    },
  },
});
